package com.itheima.employeesys.ui;

import com.itheima.employeesys.bean.Employee;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

//添加员工信息的界面
public class AddEmployeeUI extends JFrame {
    private JTextField idField;
    private JTextField nameField;
    private JComboBox<String> genderComboBox;
    private JTextField ageField;
    private JTextField phoneField;
    private JTextField positionField;
    private JTextField hireDateField;
    private JTextField salaryField;
    private JTextField departmentField;
    private JButton addButton;
    private JButton cancelButton;
    private Employee employee; // 用于返回创建的员工对象
    
    public AddEmployeeUI() {
        initializeComponents();
        setupLayout();
        setupEventHandlers();
        setFrameProperties();
    }
    
    // 重载构造函数，支持传入表格模型以自动生成ID
    public AddEmployeeUI(DefaultTableModel tableModel) {
        this(); // 调用无参构造函数
        autoGenerateId(tableModel);
    }
    
    private void initializeComponents() {
        // 初始化输入字段
        idField = new JTextField(20);
        nameField = new JTextField(20);
        genderComboBox = new JComboBox<>(new String[]{"男", "女"});
        ageField = new JTextField(20);
        phoneField = new JTextField(20);
        positionField = new JTextField(20);
        hireDateField = new JTextField(20);
        // 设置默认入职日期为今天
        hireDateField.setText(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        salaryField = new JTextField(20);
        departmentField = new JTextField(20);
        
        // 按钮
        addButton = new JButton("添加");
        cancelButton = new JButton("取消");
    }
    
    private void setupLayout() {
        setLayout(new BorderLayout());
        
        // 创建表单面板
        JPanel formPanel = new JPanel(new GridBagLayout());
        formPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 10, 10, 10);
        gbc.anchor = GridBagConstraints.WEST;
        
        // ID行
        gbc.gridx = 0; gbc.gridy = 0;
        formPanel.add(new JLabel("员工ID:"), gbc);
        gbc.gridx = 1;
        formPanel.add(idField, gbc);
        idField.setEditable(false);
        
        // 姓名行
        gbc.gridx = 0; gbc.gridy = 1;
        formPanel.add(new JLabel("姓名:"), gbc);
        gbc.gridx = 1;
        formPanel.add(nameField, gbc);
        
        // 性别行
        gbc.gridx = 0; gbc.gridy = 2;
        formPanel.add(new JLabel("性别:"), gbc);
        gbc.gridx = 1;
        formPanel.add(genderComboBox, gbc);
        
        // 年龄行
        gbc.gridx = 0; gbc.gridy = 3;
        formPanel.add(new JLabel("年龄:"), gbc);
        gbc.gridx = 1;
        formPanel.add(ageField, gbc);
        
        // 电话行
        gbc.gridx = 0; gbc.gridy = 4;
        formPanel.add(new JLabel("电话:"), gbc);
        gbc.gridx = 1;
        formPanel.add(phoneField, gbc);
        
        // 职位行
        gbc.gridx = 0; gbc.gridy = 5;
        formPanel.add(new JLabel("职位:"), gbc);
        gbc.gridx = 1;
        formPanel.add(positionField, gbc);
        
        // 入职日期行
        gbc.gridx = 0; gbc.gridy = 6;
        formPanel.add(new JLabel("入职日期:"), gbc);
        gbc.gridx = 1;
        formPanel.add(hireDateField, gbc);
        
        // 薪水行
        gbc.gridx = 0; gbc.gridy = 7;
        formPanel.add(new JLabel("薪水:"), gbc);
        gbc.gridx = 1;
        formPanel.add(salaryField, gbc);
        
        // 部门行
        gbc.gridx = 0; gbc.gridy = 8;
        formPanel.add(new JLabel("部门:"), gbc);
        gbc.gridx = 1;
        formPanel.add(departmentField, gbc);
        
        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 0));
        buttonPanel.add(addButton);
        buttonPanel.add(cancelButton);
        
        // 添加到主面板
        add(formPanel, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);
    }
    
    private void setupEventHandlers() {
        // 添加按钮事件
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (validateInput()) {
                    createEmployee();
                    JOptionPane.showMessageDialog(AddEmployeeUI.this, "员工信息添加成功！", "提示", JOptionPane.INFORMATION_MESSAGE);
                    dispose();
                }
            }
        });
        
        // 取消按钮事件
        cancelButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dispose();
            }
        });
    }
    
    // 验证输入
    private boolean validateInput() {
        if (idField.getText().trim().isEmpty() || 
            nameField.getText().trim().isEmpty() || 
            ageField.getText().trim().isEmpty() || 
            phoneField.getText().trim().isEmpty() || 
            positionField.getText().trim().isEmpty() || 
            hireDateField.getText().trim().isEmpty() || 
            salaryField.getText().trim().isEmpty() || 
            departmentField.getText().trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "请填写所有必填字段！", "提示", JOptionPane.WARNING_MESSAGE);
            return false;
        }
        
        try {
            Integer.parseInt(ageField.getText().trim());
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(this, "年龄必须是数字！", "提示", JOptionPane.WARNING_MESSAGE);
            return false;
        }
        
        try {
            Double.parseDouble(salaryField.getText().trim());
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(this, "薪水必须是数字！", "提示", JOptionPane.WARNING_MESSAGE);
            return false;
        }
        
        // 验证日期格式
        try {
            LocalDate.parse(hireDateField.getText().trim(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "日期格式应为 yyyy-MM-dd！", "提示", JOptionPane.WARNING_MESSAGE);
            return false;
        }
        
        return true;
    }
    
    // 创建员工对象
    private void createEmployee() {
        employee = new Employee(
            idField.getText().trim(),
            nameField.getText().trim(),
            (String) genderComboBox.getSelectedItem(),
            Integer.parseInt(ageField.getText().trim()),
            phoneField.getText().trim(),
            positionField.getText().trim(),
            hireDateField.getText().trim(),
            Double.parseDouble(salaryField.getText().trim()),
            departmentField.getText().trim()
        );
    }
    
    // 获取创建的员工对象
    public Employee getEmployee() {
        return employee;
    }
    
    // 添加设置字段值的方法，用于修改员工信息时填充现有数据
    public void setIdFieldText(String text) {
        idField.setText(text);
        idField.setEditable(false); // ID不允许修改
    }
    
    public void setNameFieldText(String text) {
        nameField.setText(text);
    }
    
    public void setGenderComboBoxSelectedItem(String item) {
        genderComboBox.setSelectedItem(item);
    }
    
    public void setAgeFieldText(String text) {
        ageField.setText(text);
    }
    
    public void setPhoneFieldText(String text) {
        phoneField.setText(text);
    }
    
    public void setPositionFieldText(String text) {
        positionField.setText(text);
    }
    
    public void setHireDateFieldText(String text) {
        hireDateField.setText(text);
    }
    
    public void setSalaryFieldText(String text) {
        salaryField.setText(text);
    }
    
    public void setDepartmentFieldText(String text) {
        departmentField.setText(text);
    }
    
    private void setFrameProperties() {
        setTitle("添加员工信息");
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setSize(400, 500);
        setLocationRelativeTo(null);
        setResizable(false);
    }
    
    // 设置修改模式的标题
    public void setModifyMode() {
        setTitle("修改员工信息");
        addButton.setText("修改");
    }
    
    // 自动生成下一个可用的员工ID
    private void autoGenerateId(DefaultTableModel tableModel) {
        int maxId = 0;
        for (int i = 0; i < tableModel.getRowCount(); i++) {
            String idStr = (String) tableModel.getValueAt(i, 0);
            try {
                // 假设ID格式为数字，例如"0001", "0002"等
                int id = Integer.parseInt(idStr);
                if (id > maxId) {
                    maxId = id;
                }
            } catch (NumberFormatException e) {
                // 如果ID不是纯数字格式，则跳过
                continue;
            }
        }
        // 设置下一个ID
        String nextId = String.format("%04d", maxId + 1);
        idField.setText(nextId);
    }
    
    public static void main(String[] args) {
        // 设置外观为系统默认外观
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new AddEmployeeUI().setVisible(true);
            }
        });
    }
}